package com.lh.filter;

import com.alibaba.fastjson.JSON;
import com.lh.domian.ResponseResults;
import com.lh.domian.entity.LoginUser;
import com.lh.enums.AppHttpCodeEnum;
import com.lh.utils.JwtUtil;
import com.lh.utils.RedisCache;
import com.lh.utils.WebUtils;
import io.jsonwebtoken.Claims;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @Author LuoHang
 * @Date 2022-08-26 23:36
 **/
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, @NotNull HttpServletResponse response, @NotNull FilterChain filterChain) throws ServletException, IOException {
        //获取请求头token
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)){
            //说明该接口不需要登录 直接放行
            filterChain.doFilter(request,response);
            return;
        }
        //解析获取userId
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (Exception e) {
            //token超时 或者 非法
            //响应告诉前端需要重新登录
            ResponseResults results = new ResponseResults(AppHttpCodeEnum.NEED_LOGIN.getCode(),null);
            //由于是过滤器还没有到Controller层 所以需要自己写响应不能抛出配置异常
            WebUtils.renderString(response, JSON.toJSONString(results));
            return;
        }
        //从redis中获取用户信息
        String userId = claims.getSubject();
        if (Objects.isNull(userId)){
            //如果登录过期 redis缓存过期
            ResponseResults results = new ResponseResults(AppHttpCodeEnum.NEED_LOGIN.getCode(),null);
            //由于是过滤器还没有到Controller层 所以需要自己写响应不能抛出配置异常
            WebUtils.renderString(response, JSON.toJSONString(results));
            return;
        }
        LoginUser loginUser = redisCache.getCacheObject("bloglogin:"+userId);
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }
}
